<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>QuarkChain DApp Example</title>
  <script src="https://cdn.jsdelivr.net/npm/quarkchain-web3@2.0.0/dist/quarkchain-web3.js"></script>
</head>

<body>
  <h1>Send Tx</h1>
  <form id="sendTxForm">
    <br> To:
    <br>
    <input type="text" name="to" value="0x000000000000000000000000000000000000000000000001">
    <br> Value (wei):
    <br>
    <input type="text" name="value" value="0">
    <br>
    <input type="button" value="Send Tx" onclick="sendTx()">
  </form>
</body>

<script type="text/javascript">
  (function () {

    if (typeof web3 === 'undefined') {
      const msg = "Couldn't detect web3. Make sure MetaMask is installed.";
      alert(msg);
      console.error(msg);
      return;
    }

    QuarkChain.injectWeb3(web3, "http://jrpc.devnet.quarkchain.io:38391");
  })();

  async function sendTx() {

    const mainnetNetworkId = "0x1";
    const devnetNetworkId = "0xff";

    const formEle = document.getElementById("sendTxForm");
    const rawTx = {
      gas: `0x${(30000).toString(16)}`,
      gasPrice: "0x0",
      data: "0x",
      // Will be updated according to the form
      to: "",
      value: "",
      networkId: devnetNetworkId,
      fromFullShardKey: "0x00000001",
      toFullShardKey: "0x00000001",
    };
    for (let i = 0; i < formEle.length; i += 1) {
      const element = formEle.elements[i];
      switch (element.name) {
        case "to":
          if (element.value.length !== 50 && element.value.length !== 42) {
            throw new Error("Invalid address");
          }
          rawTx.to = element.value;
          break;
        case "value":
          rawTx.value = `0x${Number(element.value).toString(16)}`;
          break;
      }
    }

    // Should be able to find tx ID in console.
    await web3.qkc.sendTransaction(rawTx, console.log);
  }
</script>

</html>
